// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
// 初始化云数据库
const db = cloud.database();


const rp = require("request-promise");

const URL = 'http://musicapi.xiecheng.live/personalized'
const playlistCollection = db.collection('playlist');

const MAX_LIMIT = 100;
// 云函数入口函数
exports.main = async(event, context) => {

  //去重
  /**
   * 去重
   * 首先取出原来的数据
   * 云函数取出只能最多一次取出100条数据
   * 
   */
  // const list = await playlistCollection.get(); //获取100条数据
  //查询全部总量
  const countResult =await playlistCollection.count();
  //得到总条数/最大条数
  const total = countResult.total / MAX_LIMIT;
  //获取到当前应该取几次
  const batchTimes = Math.ceil(total);

  const tasks = []

  for (let i = 0; i < batchTimes; i++) {
    let promise = playlistCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get();
    tasks.push(promise);
  }
  let list = {
    data: []
  }
  // 需要多次获取
  if (tasks.length > 0) {
    list = (await Promise.all(tasks)).reduce((acc, cur) => {
      return {
        data: acc.data.concat(cur.data)
      }
    })
  }
  // 获取数据
  const playlist = await rp(URL).then(res => {
    return JSON.parse(res).result;
  })
  // 对比去重
  const newData = [];
  for (let i = 0, len = playlist.length; i < len; i++) {
    let flag = true;
    for (let j = 0, lenj = list.data.length; j < lenj; j++) {
      if (playlist[i].id == list.data[j].id) {
        flag = false;
        break;
      }
    }
    console.log(flag)
    if (flag) {
      newData.push(playlist[i])
    }
  }
  //单个插入
  for (let i = 0, len = newData.length; i < len; i++) {
    //连接并上传  
    await playlistCollection.add({
      data: {
        ...newData[i],
        createTime: db.serverDate()
      }
    }).then(res => {
      console.log("插入成功")
    }).catch(err => {
      console.log("插入失败".err)
    })
  }

  return newData.length;
}